package com.niiwoo.civet.trade.service.dubbo.loan.core;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.niiwoo.asset.constant.MqConstants;
import com.niiwoo.asset.org.business.constants.OrgRabbitConstant;
import com.niiwoo.asset.org.business.dto.mq.ProjectStatusChangeDTO;
import com.niiwoo.civet.account.dto.response.AccountBaseResponse;
import com.niiwoo.civet.trade.dao.entity.AssetOrgProject;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.mapper.ProjectMapper;
import com.niiwoo.civet.trade.dto.request.loan.PushProjectRequestDTO;
import com.niiwoo.civet.trade.service.local.org.OrgProjectLocalService;
import com.niiwoo.civet.user.dto.response.organization.OrganizationBaseConfigRespDTO;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.tripod.provider.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by dengyunhui on 2018/04/26.
 */
@Slf4j
@Service
public class OrgSpeedLoanServiceImpl extends AbstractSpeedLoan {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private OrgProjectLocalService orgProjectLocalService;

    @Reference(version = "1.0.0")
    private OrganizationDubboService organizationDubboService;

    @Override
    protected void sendInstationInfo(Project project) {
        log.info("极速借机构-推标-不需要发站内信息：projectId={}", project.getProjectId());
    }

    @Override
    protected void pushProjectSuccess(PushProjectRequestDTO pushProjectRequestDTO, Project project) {
        super.pushProjectSuccess(pushProjectRequestDTO, project);
        this.sendMQForNotify(project);
    }

    @Override
    protected Map<String, Date> getProjectDateTime(Project project) {
        Map<String, Date> dtMap = new HashMap<>();
        Date startDateTime = new Date();

        AssetOrgProject assetOrgProject = orgProjectLocalService.getAsserOrgProjectFromMaster(project.getProjectId());
        if (assetOrgProject == null) {
            throw new IllegalArgumentException("assetOrgProject is null");
        }
        OrganizationBaseConfigRespDTO config = organizationDubboService.selectOrganizationBaseConfigByOrgId(assetOrgProject.getOrgId());
        if (config == null || config.getFundraisingDeadLineUnit() == null || config.getFundraisingDeadLine() == null) {
            throw new IllegalArgumentException("org config is null");
        }

        Date endDateTime;
        if (config.getFundraisingDeadLineUnit() == 0) { // 天
            endDateTime = org.apache.commons.lang3.time.DateUtils.addDays(startDateTime, config.getFundraisingDeadLine());
        } else { // 小时
            endDateTime = org.apache.commons.lang3.time.DateUtils.addHours(startDateTime, config.getFundraisingDeadLine());
        }

        dtMap.put("startDateTime", startDateTime);
        dtMap.put("endDateTime", endDateTime);
        return dtMap;
    }

    @Override
    protected AccountBaseResponse getAccountBase(Project project) {
        AssetOrgProject assetOrgProject = orgProjectLocalService.getAsserOrgProjectFromMaster(project.getProjectId());
        AccountBaseResponse accountBaseResponse = accountDubboService.loadActivedOrgAccount(project.getBorrowUserId(), assetOrgProject.getOrgId());
        if (accountBaseResponse == null) {
            throw new BizException("TRD40002");
        }
        return accountBaseResponse;
    }

    private void sendMQForNotify(Project project) {
        try {
            log.info("极速借机构-推标，MQ发送标的信息:{}", JSON.toJSONString(project));
            AssetOrgProject assetOrgProject = orgProjectLocalService.getAsserOrgProjectFromMaster(project.getProjectId());
            rabbitTemplate.convertAndSend(OrgRabbitConstant.Exchange.ORG_COMMON_DIRECT_EXCHANGE, OrgRabbitConstant.getRoutingKey(
                    OrgRabbitConstant.Exchange.ORG_COMMON_DIRECT_EXCHANGE, OrgRabbitConstant.Queue.PUSH_PROJECT_SUCCESS_NOTIFY_QUEUE), assetOrgProject.getOrderId());
            log.info("极速借机构-推标，MQ发送标的信息：projectId={}, orderId={}", project.getProjectId(), assetOrgProject.getOrderId());

            // 标的状态变更通知
            ProjectStatusChangeDTO dto = new ProjectStatusChangeDTO();
            dto.setProjectId(project.getProjectId());
            rabbitTemplate.convertAndSend(OrgRabbitConstant.Exchange.ORG_COMMON_DIRECT_EXCHANGE,
                    MqConstants.getRoutingKey(OrgRabbitConstant.Exchange.ORG_COMMON_DIRECT_EXCHANGE, OrgRabbitConstant.Queue.PROJECT_STATUS_CHANGE_NOTIFY_QUEUE), dto);
            log.info("极速借机构-推标成功，发送[标的状态变更]MQ成功，projectId={}", project.getProjectId());
        } catch (Exception e) {
            log.error("极速借机构-推标，MQ发送标的信息失败：projectId={}", project.getProjectId());
        }
    }
}
